package cn.dugcrs.basic.service.impl;

import cn.dugcrs.basic.constant.BaseConstants;
import cn.dugcrs.basic.dto.LoginDto;
import cn.dugcrs.basic.dto.RegisterDto;
import cn.dugcrs.basic.dto.WechatDto;
import cn.dugcrs.basic.exception.BusinessException;
import cn.dugcrs.basic.jwt.JwtUtils;
import cn.dugcrs.basic.jwt.LoginSuccseeObj;
import cn.dugcrs.basic.jwt.RsaUtils;
import cn.dugcrs.basic.service.ILoginService;
import cn.dugcrs.basic.utils.*;
import cn.dugcrs.system.domain.Menu;
import cn.dugcrs.system.mapper.MenuMapper;
import cn.dugcrs.system.mapper.PermissionMapper;
import cn.dugcrs.user.domain.Logininfo;
import cn.dugcrs.user.domain.User;
import cn.dugcrs.user.domain.Wxuser;
import cn.dugcrs.user.mapper.LogininfoMapper;
import cn.dugcrs.user.mapper.UserMapper;
import cn.dugcrs.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;


    /**
     * 用户账号密码登录
     * @param dto
     * @return
     */
    @Override
    public Map<String,Object> account(LoginDto dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();
        Integer type = dto.getType();
        // 空校验
        if (StringUtils.isEmpty(username)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(type)) {
            throw new BusinessException("参数不能为空！！！");
        }
        // 查找用户
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username,type);
        if (logininfo == null) {
            throw new BusinessException("账号或密码错误！");
        }
        // 比较密码
        String salt = logininfo.getSalt(); // 盐值
        String md5Pwd = MD5Utils.encrypByMd5(password + salt);
        if (!logininfo.getPassword().equals(md5Pwd)) {
            throw new BusinessException("账号或密码错误！");
        }

       /* // 记录logininfo到redis，key是token
        String token = BaseConstants.SmsCodeConstants.BUSINESS_LOGIN_PREFIX + username;
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        // 返回AjaxResult，如果登录成功，还需要返回token和loginInfo
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        // 为了安全起见，把铭感信息salt和password去空
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);*/

        return  loginSuccessHandler(logininfo);

    }

    /**
     * 处理密码验证成功后的逻辑
     * 返回登录人所拥有的按钮权限和菜单权限
     * @param logininfo
     */
    private Map<String,Object> loginSuccessHandler(Logininfo logininfo) {
        LoginSuccseeObj loginSuccseeObj = new LoginSuccseeObj();
        loginSuccseeObj.setLogininfo(logininfo);
        if (logininfo.getType() == 0) {
            // 登录人所拥有的按钮权限
            List<String> permissions =
                    permissionMapper.loadOwnPermissionsByLogininfoId(logininfo.getId());
            // 登录人所拥有的菜单权限
            List<Menu> menus =
                    menuMapper.loadOwnMenuByLogininfoId(logininfo.getId());
            loginSuccseeObj.setPermissions(permissions);
            loginSuccseeObj.setMenus(menus);
        }
        try {
            // 读取私钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile());
            // 使用私钥加密
            String jwtStr = JwtUtils.generateTokenExpireInMinutes(loginSuccseeObj, privateKey, 30);
            Map<String, Object> map = new HashMap<>();
            map.put("token",jwtStr);
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo",logininfo); // 当前登录人
            map.put("menus",loginSuccseeObj.getMenus()); // 当前登录人的菜单
            map.put("permissions",loginSuccseeObj.getPermissions()); // 当前登录人的按钮权限
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }



    }


    /**
     * 微信扫码登录
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(WechatDto dto) {
        // 获取code
        String code = dto.getCode();
        // 非空判断
        if (StringUtils.isEmpty(code)) {
            throw new BusinessException("微信授权失败！");
        }
        // 获取Token
        String tokenURL = BaseConstants.WecharConstants.GET_TOKEN_URL
                .replace("APPID", BaseConstants.WecharConstants.APPID)
                .replace("SECRET", BaseConstants.WecharConstants.SECRET)
                .replace("CODE", code);
        // 封装请求地址,发送请求
        String jsonStr = HttpClientUtils.httpGet(tokenURL);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid"); //就相当于微信号

        // 判断是否已经关联了
        Wxuser wxUser = wxuserMapper.loadByOpenId(openid);
        if(wxUser !=null && wxUser.getUserId() != null){
            // 查询Logininfo
            User user =userMapper.loadById(wxUser.getUserId());
            Logininfo logininfo = user2Logininfo(user);
            logininfo.setType(0);
            Map<String, Object> map = loginSuccessHandler(logininfo);
           /* // 如果关联了实现免密登录
            String token = BaseConstants.SmsCodeConstants.BUSINESS_LOGIN_PREFIX + user.getUsername();
            redisTemplate.opsForValue().set(token,user,30, TimeUnit.MINUTES);
            // 返回AjaxResult，如果登录成功，还需要返回token和loginInfo
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            // 为了安全起见，把铭感信息salt和password去空
            user.setSalt(null);
            user.setPassword(null);
            // 注意：key名必须为logininfo，因为主站展示名字是根据key:logininfo获取
            map.put("logininfo",user);*/
            return AjaxResult.success().setResultObj(map);
        }
        // 否则跳转到绑定页面
        String binderUrl = "?accessToken="+accessToken+"&openId="+openid;
        return AjaxResult.error().setResultObj(binderUrl);
    }

    @Override
    public Map<String, Object> binder(WechatDto dto) {
        String phone = dto.getPhone();
        String openId = dto.getOpenId();
        String code = dto.getVerifyCode();
        // 空校验

        // 判断验证码
        String key = BaseConstants.SmsCodeConstants.BUSINESS_BINDER_PREFIX + phone;
        Object smsCodeTmp = redisTemplate.opsForValue().get(key);
        String smsCodeTmps = smsCodeTmp.toString().split(":")[0];
        if(smsCodeTmps == null ){
            throw new BusinessException("无效的邮箱验证码或过期，请重新输入");
        }
        System.out.println(smsCodeTmp.toString());
        if(!code.equalsIgnoreCase(smsCodeTmps)){
            throw new BusinessException("错误的邮箱验证码，请重新输入");
        }

        // 判断用户是否已经注册
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(dto.getPhone(), 1);
        User user = null;
        if (StringUtils.isEmpty(logininfo)) {
            // 没有注册，添加t_user,t_logininfo
            // 保存数据 t_user + t_logininfo
            user = dto2User(dto.getPhone());
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        } else {
            user = userMapper.loadByLogininfoId(logininfo.getId());
        }
        // 第三次发送请求
        String wxUserUrl = BaseConstants.WecharConstants.GET_WXUSER_URL
                .replace("ACCESS_TOKEN",dto.getAccessToken())
                .replace("OPENID",dto.getOpenId());
        String wxUserStr = HttpClientUtils.httpGet(wxUserUrl);
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        // 绑定t_wxuser和t_user
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        // 免密登录即可
        // 存储reids
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo,
                30,
                TimeUnit.MINUTES
        );
        // 返回token + logininfo基本信息
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;
    }


    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        // 设置账号为普通用户
        logininfo.setType(1);
        return logininfo;
    }

    private User dto2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        // 随机生成六位数密码
        String pass = StrUtils.getComplexRandomString(6);
        // 发送请求告诉密码
        // 发送短信验证码给用户
        SmsSendUtils.sendSms(phone,"你的初始密码为：" + pass + ",请登录宠物乐园官网及时修改！");
        System.out.println(pass);
        String md5pwd = MD5Utils.encrypByMd5(pass+ salt);
        user.setSalt(salt);
        user.setPassword(md5pwd);
        return user;
    }

}
